package com.xnyzc.lhy.finance.service.impl.invoice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xnyzc.lhy.common.exception.InvoiceException;
import com.xnyzc.lhy.common.penum.invoice.EInvoiceAaStatus;
import com.xnyzc.lhy.common.penum.invoice.EInvoiceErrorCode;
import com.xnyzc.lhy.common.penum.invoice.EInvoiceOrderStatus;
import com.xnyzc.lhy.common.penum.invoice.EInvoiceStatus;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.StringUtil;
import com.xnyzc.lhy.finance.entity.invoice.InvoiceStrategy;
import com.xnyzc.lhy.finance.entity.invoice.OaSysInvoice;
import com.xnyzc.lhy.finance.entity.invoice.OaSysInvoiceApply;
import com.xnyzc.lhy.finance.entity.invoice.OaSysInvoiceDetail;
import com.xnyzc.lhy.finance.entity.invoice.OaSysInvoiceDidiApply;
import com.xnyzc.lhy.finance.entity.invoice.OaSysInvoiceInfo;
import com.xnyzc.lhy.finance.entity.invoice.OaSysInvoiceOrder;
import com.xnyzc.lhy.finance.entity.invoice.response.InvoiceApplyResult;
import com.xnyzc.lhy.finance.entity.invoice.response.InvoiceInvalidResult;
import com.xnyzc.lhy.finance.entity.invoice.response.InvoiceQueryResult;
import com.xnyzc.lhy.finance.entity.invoice.response.InvoiceQuerySuccessResponse;
import com.xnyzc.lhy.finance.entity.invoice.response.InvoiceResendResult;
import com.xnyzc.lhy.finance.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.finance.entity.params.invoice.InvoiceApplyForDiDiParam;
import com.xnyzc.lhy.finance.entity.params.invoice.InvoiceInvalidDiDiParam;
import com.xnyzc.lhy.finance.entity.params.invoice.InvoiceQueryDiDiParam;
import com.xnyzc.lhy.finance.entity.params.invoice.ResendInvoiceDiDiParam;
import com.xnyzc.lhy.finance.mapper.invoice.OaCOrderPersonalMapper;
import com.xnyzc.lhy.finance.mapper.invoice.OaSysInvoiceApplyMapper;
import com.xnyzc.lhy.finance.mapper.invoice.OaSysInvoiceDidiApplyMapper;
import com.xnyzc.lhy.finance.mapper.invoice.OaSysInvoiceOrderMapper;
import com.xnyzc.lhy.finance.service.fegin.invoice.IInvoiceService;
import com.xnyzc.lhy.finance.service.invoice.IOaSysInvoiceApplyService;
import com.xnyzc.lhy.finance.service.invoice.IOaSysInvoiceDetailService;
import com.xnyzc.lhy.finance.service.invoice.IOaSysInvoiceInfoService;
import com.xnyzc.lhy.finance.utils.InvoiceUtils;
import com.xnyzc.lhy.resource.entity.invoice.FormatFileSuccessResponse;
import com.xnyzc.lhy.resource.entity.invoice.InvoiceAaOpenParam;
import com.xnyzc.lhy.resource.entity.invoice.InvoiceAaOpenResult;
import com.xnyzc.lhy.resource.entity.invoice.InvoiceAaQueryOrCancellationParam;
import com.xnyzc.lhy.resource.entity.invoice.InvoiceErrorResponse;
import com.xnyzc.lhy.resource.entity.invoice.InvoiceFormatFileParam;
import com.xnyzc.lhy.resource.entity.invoice.InvoiceFormatFileResult;
import com.xnyzc.lhy.resource.entity.invoice.InvoiceInvalidParam;
import com.xnyzc.lhy.resource.entity.invoice.InvoiceOpenResult;
import com.xnyzc.lhy.resource.entity.invoice.InvoiceOpenSuccessResponse;
import com.xnyzc.lhy.resource.entity.invoice.InvoiceParam;
import com.xnyzc.lhy.resource.entity.invoice.ReInvoiceInvalidResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 发票申请 服务实现类
 * </p>
 *
 * @author haoyfa
 * @since 2019-10-24
 */
@Service
@Slf4j
public class OaSysInvoiceApplyServiceImpl extends ServiceImpl<OaSysInvoiceApplyMapper, OaSysInvoiceApply> implements IOaSysInvoiceApplyService {
    @Autowired
    private IInvoiceService iInvoiceService;

    @Autowired
    private IOaSysInvoiceInfoService iOaSysInvoiceInfoService;

    @Autowired
    private IOaSysInvoiceDetailService iOaSysInvoiceDetailService;

    @Autowired
    private InvoiceUtils invoiceUtils;

    @Autowired
    OaSysInvoiceApplyMapper oaSysInvoiceApplyMapper;

    @Autowired
    OaSysInvoiceOrderMapper oaSysInvoiceOrderMapper;

    @Autowired
    OaSysInvoiceDidiApplyMapper oaSysInvoiceDidiApplyMapper;

    @Autowired
    OaCOrderPersonalMapper oaCOrderPersonalMapper;

    /**
     * 发票申请
     *
     * @param invoiceApplyForDiDiParam
     * @return
     */
    @Override
    public InvoiceApplyResult getInvoiceApplyForDiDi(InvoiceApplyForDiDiParam invoiceApplyForDiDiParam) {

        if (invoiceApplyForDiDiParam.getIsRed() == null
                || !invoiceApplyForDiDiParam.getIsRed()) {
            //检查发票金额
            this.checkInvoidOrder(invoiceApplyForDiDiParam);
        }

        //获取发票创建策略
        InvoiceStrategy invoiceStrategy = invoiceUtils.getDefaultStrategy();

        //获取DiDi发票信息
        OaSysInvoice oaSysInvoice = this.getApplyDiDiInvoice(invoiceStrategy, invoiceApplyForDiDiParam);
        //创建发票订单关系
        this.createInvoiceOrder(invoiceApplyForDiDiParam.getInvoiceOrderIdsList(), oaSysInvoice.getOaSysInvoiceApply().getInvoiceApplyId());

        //创建开发票信息
        InvoiceParam invoiceParam = null;
        try {
            invoiceParam = invoiceUtils.createDiDiInvoiceParam(invoiceStrategy, invoiceApplyForDiDiParam);
        } catch (Exception ex) {
            log.error("发票服务初始化发票信息错误");
            throw InvoiceException.create(EInvoiceErrorCode.initInvoiceError);
        }

        InvoiceOpenResult openInvoiceResult = iInvoiceService.invoiceOpenRequest(invoiceParam);

        if (openInvoiceResult.getIsSuccess() == true) {
            //成功进行存储信息
            InvoiceOpenSuccessResponse invoiceOpenSuccessResponse = openInvoiceResult.getInvoiceOpenSuccessResponse();
            log.info(String.format("发票创建成功，发票编号：{0},发票流水号：{}",
                    invoiceOpenSuccessResponse.getInvoiceNo(),
                    invoiceParam.getInvoiceApplyParam().getReqSerialNumber()));

            //保存发票信息
            //发票代码
            oaSysInvoice.getOaSysInvoiceInfo().setInvoiceCode(invoiceOpenSuccessResponse.getInvoiceCode());
            //发票号码
            oaSysInvoice.getOaSysInvoiceInfo().setInvoiceNo(invoiceOpenSuccessResponse.getInvoiceNo());
            //开票日期
            oaSysInvoice.getOaSysInvoiceInfo().setInvoiceDate(invoiceUtils.strToDateLong(invoiceOpenSuccessResponse.getInvoiceDate()));
            //税控码
            oaSysInvoice.getOaSysInvoiceInfo().setTaxControlCode(invoiceOpenSuccessResponse.getTaxControlCode());
            //校验码
            oaSysInvoice.getOaSysInvoiceInfo().setInvoiceCheckCode(invoiceOpenSuccessResponse.getInvoiceCheckCode());
            //二维码
            oaSysInvoice.getOaSysInvoiceInfo().setInvoiceQrCode(invoiceOpenSuccessResponse.getInvoiceQrCode());
            //开票状态
            oaSysInvoice.getOaSysInvoiceInfo().setInvoiceStatus(EInvoiceStatus.opened.getValue());

            iOaSysInvoiceInfoService.billingSuccessfulOperation(oaSysInvoice.getOaSysInvoiceInfo());

            //创建板式文件
            InvoiceFormatFileResult createFarmatFileResult = this.createFarmatFile(oaSysInvoice);

            if (createFarmatFileResult.getIsSuccess() == true) {
                FormatFileSuccessResponse formatFileSuccessResponse = createFarmatFileResult.getFormatFileSuccessResponse();
                invoiceOpenSuccessResponse.setFileUrl(formatFileSuccessResponse.getFileUrl());

                //更新文件信息=成功
                oaSysInvoice.getOaSysInvoiceInfo().setFileUrl(formatFileSuccessResponse.getFileUrl());
                iOaSysInvoiceInfoService.billingFarmatFileOperation(oaSysInvoice.getOaSysInvoiceInfo());

                InvoiceApplyResult invoiceApplyResult = new InvoiceApplyResult();
                invoiceApplyResult.setIsSuccess(true);

                return invoiceApplyResult;
            } else {
                log.error("发票板式文件生成错误");

                InvoiceApplyResult invoiceApplyResult = new InvoiceApplyResult();
                invoiceApplyResult.setIsSuccess(false);
                invoiceApplyResult.setInvoiceErrorResponse(
                        new com.xnyzc.lhy.finance.entity.invoice.response.InvoiceErrorResponse(EInvoiceErrorCode.farmatFileError));

                return invoiceApplyResult;
            }
        } else {
            //失败存储失败信息，设置为状态=开票失败返回结果
            InvoiceErrorResponse invoiceErrorResponse = openInvoiceResult.getInvoiceErrorResponse();
            oaSysInvoice.getOaSysInvoiceInfo().setApplyFailReason(invoiceErrorResponse.getMessage());
            iOaSysInvoiceInfoService.billingFailedOperation(oaSysInvoice.getOaSysInvoiceInfo());

            InvoiceApplyResult invoiceApplyResult = new InvoiceApplyResult();
            invoiceApplyResult.setIsSuccess(false);
            invoiceApplyResult.setInvoiceErrorResponse(
                    new com.xnyzc.lhy.finance.entity.invoice.response.InvoiceErrorResponse(invoiceErrorResponse.getCode(), invoiceErrorResponse.getMessage()));

            return invoiceApplyResult;
        }
    }

    /**
     * 创建发票与订单的关联数据
     */
    private void createInvoiceOrder(String[] orderIds, Long applyId) {
        //保存发票订单关系
        if (orderIds != null
                && orderIds.length > 0) {
            List<OaSysInvoiceOrder> oaSysInvoiceOrderList = new ArrayList<>(orderIds.length);
            for (int i = 0; i < orderIds.length; i++) {
                OaSysInvoiceOrder oaSysInvoiceOrder = new OaSysInvoiceOrder();
                oaSysInvoiceOrder.setId(IDUtil.nextId());
                oaSysInvoiceOrder.setOrderId(orderIds[i]);
                oaSysInvoiceOrder.setInvoiceApplyId(applyId);

                oaSysInvoiceOrderList.add(oaSysInvoiceOrder);
            }
            oaSysInvoiceOrderMapper.insertInvoiceOrder(oaSysInvoiceOrderList);
        } else {
            log.error("发票对应的订单id错误");
            throw InvoiceException.create(EInvoiceErrorCode.orderAmountError);
        }
    }

    /**
     * 发票关联订单金额检查
     */
    private Boolean checkInvoidOrder(InvoiceApplyForDiDiParam invoiceApplyForDiDiParam) {
        //检查订单金额是否正确
        if (!"".equals(StringUtil.isNullReturnEmpty(invoiceApplyForDiDiParam.getInvoiceOrderIds()))) {
            String[] orderIds = invoiceApplyForDiDiParam.getInvoiceOrderIds().split(",");
            invoiceApplyForDiDiParam.setInvoiceOrderIdsList(orderIds);

            BigDecimal orderAmount = this.amountOrder(orderIds);
            BigDecimal invoiceAmount = new BigDecimal(invoiceApplyForDiDiParam.getInvoiceAmount());
            if (orderAmount != null
                    && invoiceAmount.compareTo(orderAmount) == 0) {
                return true;
            } else {
                log.error("开票金额与订单金额不一致");
                throw InvoiceException.create(EInvoiceErrorCode.amountError);
            }
        } else {
            log.error("发票对应的订单id错误");
            throw InvoiceException.create(EInvoiceErrorCode.orderAmountError);
        }
    }

    /**
     * 发票查询
     *
     * @param invoiceQueryDiDiParam
     * @return
     */
    @Override
    public InvoiceQueryResult getInvoiceQueryDiDi(InvoiceQueryDiDiParam invoiceQueryDiDiParam) {
        //获取发票信息
        OaSysInvoice oaSysInvoice = getDiDiQueryInvoice(invoiceQueryDiDiParam);

        if (EInvoiceStatus.opening.getValue().equals(oaSysInvoice.getOaSysInvoiceInfo().getInvoiceStatus())
                && "".equals(StringUtil.isNullReturnEmpty(oaSysInvoice.getOaSysInvoiceInfo().getFileUrl()))) {
            //创建板式文件
            InvoiceFormatFileResult invoiceResult = this.createFarmatFile(oaSysInvoice);
            FormatFileSuccessResponse formatFileSuccessResponse = invoiceResult.getFormatFileSuccessResponse();
            //开票状态
            oaSysInvoice.getOaSysInvoiceInfo().setInvoiceStatus(EInvoiceStatus.opened.getValue());
            oaSysInvoice.getOaSysInvoiceInfo().setFileUrl(formatFileSuccessResponse.getFileUrl());

            iOaSysInvoiceInfoService.billingFarmatFileOperation(oaSysInvoice.getOaSysInvoiceInfo());

        } else {
            //正常处理
        }

        //返回发票数据
        InvoiceQueryResult invoiceQueryResult = new InvoiceQueryResult();

        InvoiceQuerySuccessResponse invoiceQuerySuccessResponse = new InvoiceQuerySuccessResponse();
        //发票代码
        invoiceQuerySuccessResponse.setInvoiceCode(oaSysInvoice.getOaSysInvoiceInfo().getInvoiceCode());
        //发票号码
        invoiceQuerySuccessResponse.setInvoiceNo(oaSysInvoice.getOaSysInvoiceInfo().getInvoiceNo());
        //开票日期
        invoiceQuerySuccessResponse.setInvoiceDate(oaSysInvoice.getOaSysInvoiceInfo().getInvoiceDate().toString());
        //税控码
        invoiceQuerySuccessResponse.setTaxControlCode(oaSysInvoice.getOaSysInvoiceInfo().getTaxControlCode());
        //校验码
        invoiceQuerySuccessResponse.setInvoiceCheckCode(oaSysInvoice.getOaSysInvoiceInfo().getInvoiceCheckCode());
        //二维码
        invoiceQuerySuccessResponse.setInvoiceQrCode(oaSysInvoice.getOaSysInvoiceInfo().getInvoiceQrCode());
        //发票状态
        invoiceQuerySuccessResponse.setStatus(oaSysInvoice.getOaSysInvoiceInfo().getInvoiceStatus());
        // 发票路径
        invoiceQuerySuccessResponse.setFileUrl(oaSysInvoice.getOaSysInvoiceInfo().getFileUrl());

        invoiceQueryResult.setIsSuccess(true);
        invoiceQueryResult.setInvoiceQuerySuccessResponse(invoiceQuerySuccessResponse);

        return invoiceQueryResult;
    }

    /**
     * 发票重发
     *
     * @param resendInvoiceParam
     * @return
     */
    @Override
    public InvoiceResendResult getResendInvoiceDiDi(ResendInvoiceDiDiParam resendInvoiceParam) {
        //获取发票信息
        OaSysInvoice oaSysInvoice = getDiDiResendInvoice(resendInvoiceParam);

        if (oaSysInvoice.getOaSysInvoiceInfo() != null
                && oaSysInvoice.getOaSysInvoiceInfo().getInvoiceInfoId() != null
                && oaSysInvoice.getOaSysInvoiceInfo().getInvoiceInfoId() > 0
                && (EInvoiceStatus.opening.getValue().equals(oaSysInvoice.getOaSysInvoiceInfo().getInvoiceStatus())
                || EInvoiceStatus.opened.getValue().equals(oaSysInvoice.getOaSysInvoiceInfo().getInvoiceStatus()))) {

            oaSysInvoice.getOaSysInvoiceApply().setUserEmail(resendInvoiceParam.getEmail());

            //创建板式文件
            InvoiceFormatFileResult formatFileResult = this.createFarmatFile(oaSysInvoice);
            if (formatFileResult.getIsSuccess() == true) {
                FormatFileSuccessResponse formatFileSuccessResponse = formatFileResult.getFormatFileSuccessResponse();
                //开票状态
                oaSysInvoice.getOaSysInvoiceInfo().setInvoiceStatus(EInvoiceStatus.opened.getValue());
                oaSysInvoice.getOaSysInvoiceInfo().setFileUrl(formatFileSuccessResponse.getFileUrl());
                iOaSysInvoiceInfoService.billingFarmatFileOperation(oaSysInvoice.getOaSysInvoiceInfo());

                InvoiceResendResult invoiceResendResult = new InvoiceResendResult();
                invoiceResendResult.setIsSuccess(true);

                return invoiceResendResult;
            } else {
                InvoiceResendResult invoiceResendResult = new InvoiceResendResult();
                invoiceResendResult.setIsSuccess(false);
                InvoiceErrorResponse invoiceErrorResponse = formatFileResult.getInvoiceErrorResponse();
                invoiceResendResult.setInvoiceErrorResponse(
                        new com.xnyzc.lhy.finance.entity.invoice.response.InvoiceErrorResponse(invoiceErrorResponse.getCode(), invoiceErrorResponse.getMessage()));
                return invoiceResendResult;
            }
        } else {
            log.error("发票重发发票信息错误");
            throw InvoiceException.create(EInvoiceErrorCode.initInvoiceError);
        }
    }

    /**
     * 作废发票
     *
     * @param invoiceInvalidDiDiParam
     * @return
     */
    @Override
    public InvoiceInvalidResult getInvoiceInvalidDiDi(InvoiceInvalidDiDiParam invoiceInvalidDiDiParam) {
        //获取发票信息
        OaSysInvoiceApply oaSysInvoiceApply;
        OaSysInvoiceInfo oaSysInvoiceInfo;

        try {
            String didiInvoiceId = invoiceInvalidDiDiParam.getBlueInvoiceId();
            oaSysInvoiceApply = this.selectOaSysInvoiceApplyByDidiId(didiInvoiceId);
            if (oaSysInvoiceApply != null
                    && oaSysInvoiceApply.getInvoiceApplyId() != null
                    && oaSysInvoiceApply.getInvoiceApplyId() > 0) {
                oaSysInvoiceInfo = iOaSysInvoiceInfoService.selectOaSysInvoiceInfoByApplyId(oaSysInvoiceApply.getInvoiceApplyId());
            } else {
                log.error("获取发票信息失败");
                throw InvoiceException.create(EInvoiceErrorCode.invoiceIdError);
            }
        } catch (Exception ex) {
            log.error("获取发票信息失败");
            throw InvoiceException.create(EInvoiceErrorCode.invoiceIdError);
        }

        if (oaSysInvoiceInfo != null
                && oaSysInvoiceInfo.getInvoiceInfoId() != null
                && oaSysInvoiceInfo.getInvoiceInfoId() > 0
                && EInvoiceStatus.opened.getValue().equals(oaSysInvoiceInfo.getInvoiceStatus())) {

            //作废蓝票
            ReInvoiceInvalidResult invoiceResult;
            InvoiceInvalidParam invoiceInvalidParam = null;
            try {

                invoiceInvalidParam = invoiceUtils.createInvoiceInvalidDiDiParam(oaSysInvoiceApply, oaSysInvoiceInfo, invoiceInvalidDiDiParam);
                invoiceResult = iInvoiceService.invoiceInvalidRequest(invoiceInvalidParam);

                if (invoiceResult.getIsSuccess() == true) {
                    //发票作废操作
                    oaSysInvoiceInfo.setInvoiceStatus(EInvoiceStatus.invidi.getValue());
                    iOaSysInvoiceInfoService.invoiceInvalid(oaSysInvoiceInfo);

                    //开红票
                    OaSysInvoiceDetail oaSysInvoiceDetail = iOaSysInvoiceDetailService.selectOaSysInvoiceDetailByInfoId(oaSysInvoiceInfo.getInvoiceInfoId());
                    String redDidiInvoiceId = invoiceInvalidDiDiParam.getRedInvoiceId();
                    InvoiceApplyForDiDiParam invoiceApplyForDiDiParam = createInvoiceApplyForDiDiParam(oaSysInvoiceApply, oaSysInvoiceInfo, oaSysInvoiceDetail, redDidiInvoiceId);

                    //设置原票信息
                    invoiceApplyForDiDiParam.setIsRed(true);
                    invoiceApplyForDiDiParam.setRedInfoNo(oaSysInvoiceApply.getReqSerialNumber());
                    invoiceApplyForDiDiParam.setOriginalInvoiceCode(oaSysInvoiceInfo.getInvoiceCode());
                    invoiceApplyForDiDiParam.setOriginalInvoiceNo(oaSysInvoiceInfo.getInvoiceNo());

                    InvoiceApplyResult invoiceApplyResult = null;
                    try {
                        invoiceApplyResult = this.getInvoiceApplyForDiDi(invoiceApplyForDiDiParam);
                    } catch (InvoiceException invoiceException) {
                        log.error("开发票服务错误");
                        invoiceApplyResult = new InvoiceApplyResult();
                        invoiceApplyResult.setIsSuccess(false);

                        //返回错误信息
                        com.xnyzc.lhy.finance.entity.invoice.response.InvoiceErrorResponse invoiceErrorResponse = new com.xnyzc.lhy.finance.entity.invoice.response.InvoiceErrorResponse(
                                invoiceException.getErrno().getDesc(),
                                invoiceException.getErrmsg());
                        invoiceApplyResult.setInvoiceErrorResponse(invoiceErrorResponse);
                    }

                    if (invoiceApplyResult.getIsSuccess() == true) {
                        InvoiceInvalidResult invoiceInvalidResult = new InvoiceInvalidResult();
                        invoiceInvalidResult.setIsSuccess(true);
                        return invoiceInvalidResult;
                    } else {
                        InvoiceInvalidResult invoiceInvalidResult = new InvoiceInvalidResult();
                        invoiceInvalidResult.setIsSuccess(false);
                        invoiceInvalidResult.setInvoiceErrorResponse(invoiceApplyResult.getInvoiceErrorResponse());
                        return invoiceInvalidResult;
                    }
                } else {
                    InvoiceInvalidResult invoiceInvalidResult = new InvoiceInvalidResult();
                    invoiceInvalidResult.setIsSuccess(false);
                    InvoiceErrorResponse invoiceErrorResponse = invoiceResult.getInvoiceErrorResponse();
                    invoiceInvalidResult.setInvoiceErrorResponse(
                            new com.xnyzc.lhy.finance.entity.invoice.response.InvoiceErrorResponse(invoiceErrorResponse.getCode(), invoiceErrorResponse.getMessage()));
                    return invoiceInvalidResult;
                }

            } catch (Exception ex) {
                log.error("发票作废服务初始化发票信息错误");
                throw InvoiceException.create(EInvoiceErrorCode.initInvoiceError);
            }

        } else {
            log.error("蓝票状态不正确，无法进行红冲");
            throw InvoiceException.create(EInvoiceErrorCode.initInvoiceError);
        }
    }

    /**
     * 开具红字发票
     *
     * @param invoiceInvalidDiDiParam
     * @return
     */
    @Override
    public InvoiceInvalidResult getRedInvoiceDiDi(InvoiceInvalidDiDiParam invoiceInvalidDiDiParam) {
        //获取发票信息
        OaSysInvoiceApply oaSysInvoiceApply;
        OaSysInvoiceInfo oaSysInvoiceInfo;

        try {
            String didiInvoiceId = invoiceInvalidDiDiParam.getBlueInvoiceId();
            oaSysInvoiceApply = this.selectOaSysInvoiceApplyByDidiId(didiInvoiceId);
            if (oaSysInvoiceApply != null
                    && oaSysInvoiceApply.getInvoiceApplyId() != null
                    && oaSysInvoiceApply.getInvoiceApplyId() > 0) {
                oaSysInvoiceInfo = iOaSysInvoiceInfoService.selectOaSysInvoiceInfoByApplyId(oaSysInvoiceApply.getInvoiceApplyId());
            } else {
                log.error("获取发票信息失败");
                throw InvoiceException.create(EInvoiceErrorCode.invoiceIdError);
            }
        } catch (Exception ex) {
            log.error("获取发票信息失败");
            throw InvoiceException.create(EInvoiceErrorCode.invoiceIdError);
        }

        if (oaSysInvoiceInfo != null
                && oaSysInvoiceInfo.getInvoiceInfoId() != null
                && oaSysInvoiceInfo.getInvoiceInfoId() > 0
                && EInvoiceStatus.opened.getValue().equals(oaSysInvoiceInfo.getInvoiceStatus())) {
            //作废蓝票
            try {
                //开红票
                OaSysInvoiceDetail oaSysInvoiceDetail = iOaSysInvoiceDetailService.selectOaSysInvoiceDetailByInfoId(oaSysInvoiceInfo.getInvoiceInfoId());
                String redDidiInvoiceId = invoiceInvalidDiDiParam.getRedInvoiceId();
                InvoiceApplyForDiDiParam invoiceApplyForDiDiParam = createInvoiceApplyForDiDiParam(oaSysInvoiceApply, oaSysInvoiceInfo, oaSysInvoiceDetail, redDidiInvoiceId);

                //设置原票信息
                invoiceApplyForDiDiParam.setIsRed(true);
                invoiceApplyForDiDiParam.setRedInfoNo(oaSysInvoiceApply.getReqSerialNumber());
                invoiceApplyForDiDiParam.setOriginalInvoiceCode(oaSysInvoiceInfo.getInvoiceCode());
                invoiceApplyForDiDiParam.setOriginalInvoiceNo(oaSysInvoiceInfo.getInvoiceNo());

                InvoiceApplyResult invoiceApplyResult = null;
                try {
                    invoiceApplyResult = this.getInvoiceApplyForDiDi(invoiceApplyForDiDiParam);
                } catch (InvoiceException invoiceException) {
                    log.error("开红字发票服务错误");
                    invoiceApplyResult = new InvoiceApplyResult();
                    invoiceApplyResult.setIsSuccess(false);

                    //返回错误信息
                    com.xnyzc.lhy.finance.entity.invoice.response.InvoiceErrorResponse invoiceErrorResponse = new com.xnyzc.lhy.finance.entity.invoice.response.InvoiceErrorResponse(
                            invoiceException.getErrno().getDesc(),
                            invoiceException.getErrmsg());
                    invoiceApplyResult.setInvoiceErrorResponse(invoiceErrorResponse);
                }

                if (invoiceApplyResult.getIsSuccess() == true) {
                    //发票作废操作
                    oaSysInvoiceInfo.setInvoiceStatus(EInvoiceStatus.invidi.getValue());
                    iOaSysInvoiceInfoService.invoiceInvalid(oaSysInvoiceInfo);

                    InvoiceInvalidResult invoiceInvalidResult = new InvoiceInvalidResult();
                    invoiceInvalidResult.setIsSuccess(true);
                    return invoiceInvalidResult;
                } else {
                    InvoiceInvalidResult invoiceInvalidResult = new InvoiceInvalidResult();
                    invoiceInvalidResult.setIsSuccess(false);
                    invoiceInvalidResult.setInvoiceErrorResponse(invoiceApplyResult.getInvoiceErrorResponse());
                    return invoiceInvalidResult;
                }

            } catch (Exception ex) {
                log.error("发票作废服务初始化发票信息错误");
                throw InvoiceException.create(EInvoiceErrorCode.initInvoiceError);
            }

        } else {
            log.error("蓝票状态不正确，无法进行红冲");
            throw InvoiceException.create(EInvoiceErrorCode.initInvoiceError);
        }
    }

    /**
     * 创建红票创建信息
     *
     * @param oaSysInvoiceApply
     * @param oaSysInvoiceInfo
     * @return
     */
    private InvoiceApplyForDiDiParam createInvoiceApplyForDiDiParam(OaSysInvoiceApply oaSysInvoiceApply, OaSysInvoiceInfo oaSysInvoiceInfo, OaSysInvoiceDetail oaSysInvoiceDetail, String redInvoiceId) {
        InvoiceApplyForDiDiParam invoiceApplyForDiDiParam = new InvoiceApplyForDiDiParam();
        /**
         * 滴滴方唯一发票编号
         */
        invoiceApplyForDiDiParam.setInvoiceId(redInvoiceId);

        /**
         * 发票抬头
         */
        invoiceApplyForDiDiParam.setInvoiceTitle(oaSysInvoiceInfo.getBuyerName());

        /**
         * 金额
         */
        invoiceApplyForDiDiParam.setInvoiceAmount(oaSysInvoiceDetail.getGoodsTotalPrice().toString());

        /**
         * 开票类型 1个人2公司
         */
        invoiceApplyForDiDiParam.setInvoiceType(oaSysInvoiceInfo.getInvoiceClass());

        /**
         * 纳税人识别号
         */
        invoiceApplyForDiDiParam.setCustomerIdentifier(oaSysInvoiceInfo.getBuyerTaxNo());

        return invoiceApplyForDiDiParam;
    }

    /**
     * 创建红字发票
     *
     * @return
     */
    public OaSysInvoiceInfo createRedInvoice(OaSysInvoiceInfo oldOaSysInvoiceInfo) {
        OaSysInvoiceInfo newOaSysInvoiceInfo = new OaSysInvoiceInfo();
        return newOaSysInvoiceInfo;
    }


    /**
     * 根据滴滴发票id获取发票申请记录
     */
    @Override
    public OaSysInvoiceApply selectOaSysInvoiceApplyByDidiId(String didiinvoiceId) {
        try {
            QueryWrapper queryWrapper = new QueryWrapper();

            queryWrapper.eq(OaSysInvoiceApply.SERIAL_NO, didiinvoiceId);
            OaSysInvoiceApply oaSysInvoiceApply = oaSysInvoiceApplyMapper.selectOne(queryWrapper);
            return oaSysInvoiceApply;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 根据发票信息创建板式文件
     *
     * @param oaSysInvoice
     * @return
     */
    private InvoiceFormatFileResult createFarmatFile(OaSysInvoice oaSysInvoice) {
        InvoiceFormatFileParam invoiceFormatFileParam = null;

        try {
            invoiceFormatFileParam = invoiceUtils.createInvoiceFormatFileParam(oaSysInvoice);
            return iInvoiceService.formatfileBuildRequest(invoiceFormatFileParam);
        } catch (Exception ex) {
            log.error("发票板式文件生成错误");
            throw InvoiceException.create(EInvoiceErrorCode.farmatFileError);
        }
    }

    /**
     * 获取发票DiDi发票是否存在
     *
     * @return
     */
    private OaSysInvoice getApplyDiDiInvoice(InvoiceStrategy invoiceStrategy, InvoiceApplyForDiDiParam invoiceApplyForDiDiParam) {
        OaSysInvoiceApply oaSysInvoiceApply;
        OaSysInvoiceInfo oaSysInvoiceInfo;
        OaSysInvoiceDetail oaSysInvoiceDetail;

        try {
            String didiInvoiceId = invoiceApplyForDiDiParam.getInvoiceId();
            oaSysInvoiceApply = this.selectOaSysInvoiceApplyByDidiId(didiInvoiceId);
            if (oaSysInvoiceApply != null
                    && oaSysInvoiceApply.getInvoiceApplyId() != null
                    && oaSysInvoiceApply.getInvoiceApplyId() > 0) {
                oaSysInvoiceInfo = iOaSysInvoiceInfoService.selectOaSysInvoiceInfoByApplyId(oaSysInvoiceApply.getInvoiceApplyId());

                if (oaSysInvoiceInfo != null
                        && oaSysInvoiceInfo.getInvoiceInfoId() != null
                        && oaSysInvoiceInfo.getInvoiceInfoId() > 0
                        && (EInvoiceStatus.opening.getValue().equals(oaSysInvoiceInfo.getInvoiceStatus())
                        || EInvoiceStatus.opened.getValue().equals(oaSysInvoiceInfo.getInvoiceStatus())
                        || EInvoiceStatus.invidi.getValue().equals(oaSysInvoiceInfo.getInvoiceStatus()))) {
                    log.error("开发票错误，发票已经存在。");
                    throw InvoiceException.create(EInvoiceErrorCode.existError);
                } else {
                    //删除错误的发票
                    iOaSysInvoiceInfoService.deletOaSysInvoiceById(oaSysInvoiceApply.getInvoiceApplyId());

                    //创建发票业务信息信息
                    oaSysInvoiceApply = invoiceUtils.createOaSysInvoiceApply(invoiceStrategy, invoiceApplyForDiDiParam);
                    oaSysInvoiceInfo = invoiceUtils.createOaSysInvoiceInfo(invoiceStrategy, invoiceApplyForDiDiParam);
                    oaSysInvoiceDetail = invoiceUtils.createOaSysInvoiceDetail(invoiceStrategy, invoiceApplyForDiDiParam);

                    //创建发票信息
                    iOaSysInvoiceInfoService.createInvoiceInfo(oaSysInvoiceApply, oaSysInvoiceInfo, oaSysInvoiceDetail);
                }

            } else {
                //创建发票业务信息信息
                oaSysInvoiceApply = invoiceUtils.createOaSysInvoiceApply(invoiceStrategy, invoiceApplyForDiDiParam);
                oaSysInvoiceInfo = invoiceUtils.createOaSysInvoiceInfo(invoiceStrategy, invoiceApplyForDiDiParam);
                oaSysInvoiceDetail = invoiceUtils.createOaSysInvoiceDetail(invoiceStrategy, invoiceApplyForDiDiParam);

                //创建发票信息
                iOaSysInvoiceInfoService.createInvoiceInfo(oaSysInvoiceApply, oaSysInvoiceInfo, oaSysInvoiceDetail);
            }
        } catch (Exception ex) {
            log.error("DIDI发票处理失败");
            throw InvoiceException.create(EInvoiceErrorCode.invoiceIdError);
        }

        OaSysInvoice oaSysInvoice = new OaSysInvoice();
        oaSysInvoice.setOaSysInvoiceApply(oaSysInvoiceApply);
        oaSysInvoice.setOaSysInvoiceInfo(oaSysInvoiceInfo);
        oaSysInvoice.setOaSysInvoiceDetail(oaSysInvoiceDetail);
        return oaSysInvoice;
    }

    /**
     * 获取滴滴查询的业务发票信息
     *
     * @param invoiceQueryDiDiParam
     * @return
     */
    private OaSysInvoice getDiDiQueryInvoice(InvoiceQueryDiDiParam invoiceQueryDiDiParam) {
        //获取发票信息
        OaSysInvoiceApply oaSysInvoiceApply;
        OaSysInvoiceInfo oaSysInvoiceInfo;

        try {
            String didiInvoiceId = invoiceQueryDiDiParam.getInvoiceId();
            oaSysInvoiceApply = this.selectOaSysInvoiceApplyByDidiId(didiInvoiceId);
            if (oaSysInvoiceApply != null
                    && oaSysInvoiceApply.getInvoiceApplyId() != null
                    && oaSysInvoiceApply.getInvoiceApplyId() > 0) {
                oaSysInvoiceInfo = iOaSysInvoiceInfoService.selectOaSysInvoiceInfoByApplyId(oaSysInvoiceApply.getInvoiceApplyId());

                if (oaSysInvoiceInfo != null
                        && oaSysInvoiceInfo.getInvoiceInfoId() != null
                        && oaSysInvoiceInfo.getInvoiceInfoId() > 0) {

                    OaSysInvoice oaSysInvoice = new OaSysInvoice();
                    oaSysInvoice.setOaSysInvoiceApply(oaSysInvoiceApply);
                    oaSysInvoice.setOaSysInvoiceInfo(oaSysInvoiceInfo);
                    return oaSysInvoice;
                } else {
                    log.error("发票信息错误，请重新申请");
                    throw InvoiceException.create(EInvoiceErrorCode.existError);
                }

            } else {
                log.error("发票不存在，请重新确认");
                throw InvoiceException.create(EInvoiceErrorCode.notExistError);
            }
        } catch (Exception ex) {
            log.error("DIDI发票处理失败");
            throw InvoiceException.create(EInvoiceErrorCode.invoiceIdError);
        }
    }

    /**
     * 获取DiDi重发发票信息
     */
    private OaSysInvoice getDiDiResendInvoice(ResendInvoiceDiDiParam resendInvoiceParam) {
        OaSysInvoiceApply oaSysInvoiceApply;
        OaSysInvoiceInfo oaSysInvoiceInfo;

        try {
            String didiInvoiceId = resendInvoiceParam.getInvoiceId();
            oaSysInvoiceApply = this.selectOaSysInvoiceApplyByDidiId(didiInvoiceId);
            if (oaSysInvoiceApply != null
                    && oaSysInvoiceApply.getInvoiceApplyId() != null
                    && oaSysInvoiceApply.getInvoiceApplyId() > 0) {
                oaSysInvoiceInfo = iOaSysInvoiceInfoService.selectOaSysInvoiceInfoByApplyId(oaSysInvoiceApply.getInvoiceApplyId());
            } else {
                log.error("获取发票信息失败");
                throw InvoiceException.create(EInvoiceErrorCode.invoiceIdError);
            }
        } catch (Exception ex) {
            log.error("获取发票信息失败");
            throw InvoiceException.create(EInvoiceErrorCode.invoiceIdError);
        }

        OaSysInvoice oaSysInvoice = new OaSysInvoice();
        oaSysInvoice.setOaSysInvoiceApply(oaSysInvoiceApply);
        oaSysInvoice.setOaSysInvoiceInfo(oaSysInvoiceInfo);
        return oaSysInvoice;
    }

    /**
     * 计算订单金额
     *
     * @param orderIdsStr
     * @return
     */
    private BigDecimal amountOrder(String[] orderIdsStr) {
        return oaSysInvoiceOrderMapper.amountOrder(orderIdsStr);
    }


    /**
     * AA发票申请
     *
     * @param invoiceApplyForDiDiParam
     * @return
     */
    @Override
    public InvoiceApplyResult getInvoiceAaApplyForDiDi(InvoiceApplyForDiDiParam invoiceApplyForDiDiParam) {

        // 整理请求参数
        InvoiceAaOpenParam invoiceAaOpenParam = new InvoiceAaOpenParam();
        int amount = (new BigDecimal(invoiceApplyForDiDiParam.getInvoiceAmount()).multiply(new BigDecimal(100))).intValue();
        invoiceAaOpenParam.setTitle(invoiceApplyForDiDiParam.getInvoiceTitle());
        invoiceAaOpenParam.setBuyer_type(Integer.valueOf(invoiceApplyForDiDiParam.getInvoiceType()));
        invoiceAaOpenParam.setTax_number(invoiceApplyForDiDiParam.getCustomerIdentifier());
        invoiceAaOpenParam.setAmount(amount);
        invoiceAaOpenParam.setReceive_email(invoiceApplyForDiDiParam.getEmail());
        invoiceAaOpenParam.setInvoice_id(invoiceApplyForDiDiParam.getInvoiceId());
        invoiceAaOpenParam.setRegister_address(invoiceApplyForDiDiParam.getRegisteAddress());
        invoiceAaOpenParam.setRegister_phone(invoiceApplyForDiDiParam.getRegistePhone());
        invoiceAaOpenParam.setOpen_bank(invoiceApplyForDiDiParam.getBankName());
        invoiceAaOpenParam.setBank_account(invoiceApplyForDiDiParam.getBankAccount());
        invoiceAaOpenParam.setRemark(invoiceApplyForDiDiParam.getInvoiceRemark());

        // 调用开票接口
        InvoiceAaOpenResult invoiceAaOpenResult = iInvoiceService.invoiceAaOpenRequest(invoiceAaOpenParam);

        InvoiceApplyResult invoiceApplyResult = new InvoiceApplyResult();
        // 开票成功
        if (invoiceAaOpenResult.getCode() == 0) {
            // 保存开票信息
            saveInvoiceRecord(invoiceApplyForDiDiParam, invoiceAaOpenResult);

            // 更新订单开票状态
            String[] orderNos = invoiceApplyForDiDiParam.getInvoiceOrderIds().split(",");
            ArrayList<String> orderNoList = new ArrayList<>(Arrays.asList(orderNos));
            UpdateWrapper<OaCOrderPersonal> oaCOrderPersonalUpdateWrapper = new UpdateWrapper<>();
            oaCOrderPersonalUpdateWrapper.in(OaCOrderPersonal.ORDER_NO, orderNoList);
            OaCOrderPersonal oaCOrderPersonal = new OaCOrderPersonal();
            oaCOrderPersonal.setUpdateTime(new Date());
            oaCOrderPersonal.setInvoiceStatus(EInvoiceOrderStatus.opening.getValue());
            oaCOrderPersonalMapper.update(oaCOrderPersonal, oaCOrderPersonalUpdateWrapper);

            invoiceApplyResult.setIsSuccess(true);
        } else {
            invoiceApplyResult.setIsSuccess(false);
        }

        return invoiceApplyResult;
    }

    /**
     * 查询发票信息
     *
     * @param invoiceQueryDiDiParam
     * @return
     */
    @Override
    public InvoiceQueryResult getInvoiceAaQueryDiDi(InvoiceQueryDiDiParam invoiceQueryDiDiParam) {

        // 查询开票记录
        List<OaSysInvoiceDidiApply> oaSysInvoiceDidiApplyList = getOaSysInvoiceDidiApplies(invoiceQueryDiDiParam);

        // 返回发票数据
        InvoiceQueryResult invoiceQueryResult = new InvoiceQueryResult();
        InvoiceQuerySuccessResponse invoiceQuerySuccessResponse = new InvoiceQuerySuccessResponse();

        if (CheckUtil.collectionIsNotEmpty(oaSysInvoiceDidiApplyList)) {
            OaSysInvoiceDidiApply oaSysInvoiceDidiApply = oaSysInvoiceDidiApplyList.get(0);
            // 查询发票信息
            InvoiceAaQueryOrCancellationParam invoiceAaQueryOrCancellationParam = new InvoiceAaQueryOrCancellationParam();
            invoiceAaQueryOrCancellationParam.setInvoice_id(oaSysInvoiceDidiApply.getBlueInvoiceId());
            InvoiceAaOpenResult invoiceAaOpenResult = iInvoiceService.getInvoiceAaQuery(invoiceAaQueryOrCancellationParam);
            // 查询成功
            if (invoiceAaOpenResult.getCode() == 0
                    && CheckUtil.objIsNotEmpty(invoiceAaOpenResult.getResult(), invoiceAaOpenResult.getResult().getInvoice_id())) {
                // 查询关联订单
                if (CheckUtil.collectionIsNotEmpty(oaSysInvoiceDidiApplyList) && oaSysInvoiceDidiApplyList.size() == 1) {
                    OaCOrderPersonal oaCOrderPersonal = new OaCOrderPersonal();
                    String orderNos = oaSysInvoiceDidiApply.getInvoiceOrderIds();
                    String[] orderList = orderNos.split(",");

                    // 整理发票查询结果
                    invoiceQueryResult(invoiceQuerySuccessResponse, oaSysInvoiceDidiApply, invoiceAaOpenResult, oaCOrderPersonal);

                    // 返回滴滴数据
                    if (Objects.equals(invoiceQueryDiDiParam.getInvoiceId(), oaSysInvoiceDidiApply.getBlueInvoiceId())) {
                        // 滴滴返回参数
                        // pdf
                        invoiceQuerySuccessResponse.setFileUrl(oaSysInvoiceDidiApply.getBluePdfUrl());
                        //发票代码
                        invoiceQuerySuccessResponse.setInvoiceCode(oaSysInvoiceDidiApply.getBlueInvoiceCode());
                        //发票号码
                        invoiceQuerySuccessResponse.setInvoiceNo(oaSysInvoiceDidiApply.getBlueInvoiceNum());
                        // 效验码
                        invoiceQuerySuccessResponse.setInvoiceCheckCode(oaSysInvoiceDidiApply.getBlueVerifyCode());
                    } else if (Objects.equals(invoiceQueryDiDiParam.getInvoiceId(), oaSysInvoiceDidiApply.getRedInvoiceId())) {
                        // 滴滴返回参数
                        // pdf
                        invoiceQuerySuccessResponse.setFileUrl(oaSysInvoiceDidiApply.getRedPdfUrl());
                        //发票代码
                        invoiceQuerySuccessResponse.setInvoiceCode(oaSysInvoiceDidiApply.getRedInvoiceCode());
                        //发票号码
                        invoiceQuerySuccessResponse.setInvoiceNo(oaSysInvoiceDidiApply.getRedInvoiceNum());
                        // 效验码
                        invoiceQuerySuccessResponse.setInvoiceCheckCode(oaSysInvoiceDidiApply.getRedVerifyCode());
                    }

                    Date date = new Date();
                    // 更新记录表
                    oaSysInvoiceDidiApply.setStatus(invoiceAaOpenResult.getResult().getStatus());
                    oaSysInvoiceDidiApply.setUpdateTime(date);
                    oaSysInvoiceDidiApplyMapper.updateById(oaSysInvoiceDidiApply);
                    // 更新订单表
                    oaCOrderPersonal.setUpdateTime(date);
                    ArrayList<String> orderNoList = new ArrayList<>(Arrays.asList(orderList));
                    UpdateWrapper<OaCOrderPersonal> oaCOrderPersonalUpdateWrapper = new UpdateWrapper<>();
                    oaCOrderPersonalUpdateWrapper.in(OaCOrderPersonal.ORDER_NO, orderNoList);
                    oaCOrderPersonalMapper.update(oaCOrderPersonal, oaCOrderPersonalUpdateWrapper);

                    invoiceQueryResult.setIsSuccess(true);
                    invoiceQueryResult.setInvoiceQuerySuccessResponse(invoiceQuerySuccessResponse);
                } else {
                    invoiceQueryResult.setIsSuccess(false);
                }
            } else {
                invoiceQueryResult.setIsSuccess(false);
            }
        } else {
            invoiceQueryResult.setIsSuccess(false);
        }

        return invoiceQueryResult;
    }

    /**
     * 整理发票查询结果
     *
     * @param invoiceQuerySuccessResponse
     * @param oaSysInvoiceDidiApply
     * @param invoiceAaOpenResult
     * @param oaCOrderPersonal
     */
    private void invoiceQueryResult(InvoiceQuerySuccessResponse invoiceQuerySuccessResponse, OaSysInvoiceDidiApply oaSysInvoiceDidiApply, InvoiceAaOpenResult invoiceAaOpenResult, OaCOrderPersonal oaCOrderPersonal) {
        // 开票成功
        if (invoiceAaOpenResult.getResult().getStatus() == EInvoiceAaStatus.openSuccess.getValue()) {
            oaCOrderPersonal.setInvoiceStatus(EInvoiceOrderStatus.openSuccess.getValue());
            // 发票记录
            oaSysInvoiceDidiApply.setBlueInvoiceCode(invoiceAaOpenResult.getResult().getInvoice_code());
            oaSysInvoiceDidiApply.setBlueInvoiceNum(invoiceAaOpenResult.getResult().getInvoice_num());
            oaSysInvoiceDidiApply.setBlueVerifyCode(invoiceAaOpenResult.getResult().getVerify_code());
            oaSysInvoiceDidiApply.setBluePdfUrl(invoiceAaOpenResult.getResult().getPdf_url());

            invoiceQuerySuccessResponse.setStatus(EInvoiceStatus.opened.getValue());
            invoiceQuerySuccessResponse.setStatusMessage(EInvoiceStatus.opened.getDesc());
        }
        // 作废成功
        else if (invoiceAaOpenResult.getResult().getStatus() == EInvoiceAaStatus.invalidSuccess.getValue()) {
            oaCOrderPersonal.setInvoiceStatus(EInvoiceOrderStatus.invalidSuccess.getValue());
            // 发票记录
            oaSysInvoiceDidiApply.setRedInvoiceCode(invoiceAaOpenResult.getResult().getInvoice_code());
            oaSysInvoiceDidiApply.setRedInvoiceNum(invoiceAaOpenResult.getResult().getInvoice_num());
            oaSysInvoiceDidiApply.setRedVerifyCode(invoiceAaOpenResult.getResult().getVerify_code());
            oaSysInvoiceDidiApply.setRedPdfUrl(invoiceAaOpenResult.getResult().getPdf_url());

            // 滴滴返回参数
            invoiceQuerySuccessResponse.setStatus(EInvoiceStatus.invidi.getValue());
            invoiceQuerySuccessResponse.setStatusMessage(EInvoiceStatus.invidi.getDesc());
        }
        // 开票中
        else if (invoiceAaOpenResult.getResult().getStatus() == EInvoiceAaStatus.opening.getValue()) {
            oaCOrderPersonal.setInvoiceStatus(EInvoiceOrderStatus.opening.getValue());
            // 滴滴返回参数
            invoiceQuerySuccessResponse.setStatus(EInvoiceStatus.opening.getValue());
            invoiceQuerySuccessResponse.setStatusMessage(EInvoiceStatus.opening.getDesc());
        }
        // 开票失败
        else if (invoiceAaOpenResult.getResult().getStatus() == EInvoiceAaStatus.openFail.getValue()) {
            oaCOrderPersonal.setInvoiceStatus(EInvoiceOrderStatus.opened.getValue());
            // 滴滴返回参数
            invoiceQuerySuccessResponse.setStatus(EInvoiceStatus.openFail.getValue());
            invoiceQuerySuccessResponse.setStatusMessage(EInvoiceStatus.openFail.getDesc());
        }
        // 作废中
        else if (invoiceAaOpenResult.getResult().getStatus() == EInvoiceAaStatus.invaliding.getValue()) {
            oaCOrderPersonal.setInvoiceStatus(EInvoiceOrderStatus.invaliding.getValue());
            // 滴滴返回参数
            invoiceQuerySuccessResponse.setStatus(EInvoiceStatus.reding.getValue());
            invoiceQuerySuccessResponse.setStatusMessage(EInvoiceStatus.reding.getDesc());
        }
        // 作废失败
        else if (invoiceAaOpenResult.getResult().getStatus() == EInvoiceAaStatus.invalidFail.getValue()) {
            oaCOrderPersonal.setInvoiceStatus(EInvoiceOrderStatus.openSuccess.getValue());
            // 滴滴返回参数
            invoiceQuerySuccessResponse.setStatus(EInvoiceStatus.openFail.getValue());
            invoiceQuerySuccessResponse.setStatusMessage(EInvoiceStatus.openFail.getDesc());
        }
    }

    /**
     * 查询开票记录
     *
     * @param invoiceQueryDiDiParam
     * @return
     */
    private List<OaSysInvoiceDidiApply> getOaSysInvoiceDidiApplies(InvoiceQueryDiDiParam invoiceQueryDiDiParam) {
        QueryWrapper<OaSysInvoiceDidiApply> oaSysInvoiceDidiApplyWrapper = new QueryWrapper<>();
        oaSysInvoiceDidiApplyWrapper.and(i -> i.eq(OaSysInvoiceDidiApply.BLUE_INVOICE_ID, invoiceQueryDiDiParam.getInvoiceId())
                .or().eq(OaSysInvoiceDidiApply.RED_INVOICE_ID, invoiceQueryDiDiParam.getInvoiceId()));
        return oaSysInvoiceDidiApplyMapper.selectList(oaSysInvoiceDidiApplyWrapper);
    }

    /**
     * 保存开票信息
     *
     * @param invoiceApplyForDiDiParam
     * @param invoiceAaOpenResult
     */
    private void saveInvoiceRecord(InvoiceApplyForDiDiParam invoiceApplyForDiDiParam, InvoiceAaOpenResult invoiceAaOpenResult) {
        OaSysInvoiceDidiApply oaSysInvoiceDidiApply = new OaSysInvoiceDidiApply();
        Long id = IDUtil.nextId();
        Date date = new Date();
        oaSysInvoiceDidiApply.setRecordId(id);
        oaSysInvoiceDidiApply.setInvoiceAmount(invoiceApplyForDiDiParam.getInvoiceAmount());
        oaSysInvoiceDidiApply.setBlueInvoiceId(invoiceApplyForDiDiParam.getInvoiceId());
        oaSysInvoiceDidiApply.setInvoiceTitle(invoiceApplyForDiDiParam.getInvoiceTitle());
        oaSysInvoiceDidiApply.setInvoiceType(invoiceApplyForDiDiParam.getInvoiceType());
        oaSysInvoiceDidiApply.setInvoiceOrderIds(invoiceApplyForDiDiParam.getInvoiceOrderIds());
        oaSysInvoiceDidiApply.setEmail(invoiceApplyForDiDiParam.getEmail());
        oaSysInvoiceDidiApply.setCustomerIdentifier(invoiceApplyForDiDiParam.getCustomerIdentifier());
        oaSysInvoiceDidiApply.setBankName(invoiceApplyForDiDiParam.getBankName());
        oaSysInvoiceDidiApply.setBankAccount(invoiceApplyForDiDiParam.getBankAccount());
        oaSysInvoiceDidiApply.setRegisteAddres(invoiceApplyForDiDiParam.getRegisteAddress());
        oaSysInvoiceDidiApply.setRegistePhone(invoiceApplyForDiDiParam.getRegistePhone());
        oaSysInvoiceDidiApply.setInvoiceRemark(invoiceApplyForDiDiParam.getInvoiceRemark());
        oaSysInvoiceDidiApply.setStatus(EInvoiceAaStatus.opening.getValue());
        oaSysInvoiceDidiApply.setCreateUser(id);
        oaSysInvoiceDidiApply.setCreateTime(date);
        oaSysInvoiceDidiApply.setUpdateUser(id);
        oaSysInvoiceDidiApply.setUpdateTime(date);
        oaSysInvoiceDidiApplyMapper.insert(oaSysInvoiceDidiApply);
    }

    /**
     * 发票作废
     *
     * @param invoiceInvalidDiDiParam
     * @return
     */
    @Override
    public InvoiceInvalidResult getRedInvoiceAaDiDi(InvoiceInvalidDiDiParam invoiceInvalidDiDiParam) {

        // 作废发票
        InvoiceAaQueryOrCancellationParam invoiceAaQueryOrCancellationParam = new InvoiceAaQueryOrCancellationParam();
        invoiceAaQueryOrCancellationParam.setInvoice_id(invoiceInvalidDiDiParam.getBlueInvoiceId());
        InvoiceAaOpenResult invoiceAaOpenResult = iInvoiceService.invoiceAaCancellation(invoiceAaQueryOrCancellationParam);
        InvoiceInvalidResult invoiceInvalidResult = new InvoiceInvalidResult();

        // 作废成功
        if (invoiceAaOpenResult.getCode() == 0) {
            // 查询关联订单
            QueryWrapper<OaSysInvoiceDidiApply> oaSysInvoiceDidiApplyWrapper = new QueryWrapper<>();
            oaSysInvoiceDidiApplyWrapper.eq(OaSysInvoiceDidiApply.BLUE_INVOICE_ID, invoiceInvalidDiDiParam.getBlueInvoiceId());
            List<OaSysInvoiceDidiApply> oaSysInvoiceDidiApplyList = oaSysInvoiceDidiApplyMapper.selectList(oaSysInvoiceDidiApplyWrapper);
            if (CheckUtil.collectionIsNotEmpty(oaSysInvoiceDidiApplyList) && oaSysInvoiceDidiApplyList.size() == 1) {
                OaSysInvoiceDidiApply oaSysInvoiceDidiApply = oaSysInvoiceDidiApplyList.get(0);

                OaCOrderPersonal oaCOrderPersonal = new OaCOrderPersonal();

                String orderNos = oaSysInvoiceDidiApply.getInvoiceOrderIds();
                String[] orderList = orderNos.split(",");


                Date date = new Date();
                // 更新记录表
                oaSysInvoiceDidiApply.setRedInvoiceId(invoiceInvalidDiDiParam.getRedInvoiceId());
                oaSysInvoiceDidiApply.setUpdateTime(date);
                oaSysInvoiceDidiApply.setStatus(EInvoiceAaStatus.invaliding.getValue());
                oaSysInvoiceDidiApplyMapper.updateById(oaSysInvoiceDidiApply);
                // 更新订单表
                oaCOrderPersonal.setInvoiceStatus(EInvoiceOrderStatus.invaliding.getValue());
                oaCOrderPersonal.setUpdateTime(date);
                ArrayList<String> orderNoList = new ArrayList<>(Arrays.asList(orderList));
                UpdateWrapper<OaCOrderPersonal> oaCOrderPersonalUpdateWrapper = new UpdateWrapper<>();
                oaCOrderPersonalUpdateWrapper.in(OaCOrderPersonal.ORDER_NO, orderNoList);
                oaCOrderPersonalMapper.update(oaCOrderPersonal, oaCOrderPersonalUpdateWrapper);

                invoiceInvalidResult.setIsSuccess(true);
            } else {
                invoiceInvalidResult.setIsSuccess(false);
            }
        }

        return invoiceInvalidResult;
    }


}
